package java8.stream.demo08numericstream;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author ChangLiang
 * @date 2020/4/23
 */
public class AppTest {

    Stream<Integer> stream;

    @BeforeEach
    public void setUp(){
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
    }

    @Test
    @DisplayName("test using integer to do box")
    public void test(){
        Integer result = stream.filter(i -> i.intValue() > 3).reduce(0, Integer::sum);
        System.out.println(result);
    }

    @Test
    @DisplayName("test mapToInt")
    public void test2() {
        IntStream intStream = stream.mapToInt(i -> i.intValue());
        int sum = intStream.filter(i -> i > 3).sum();
        System.out.println(sum);

        int result = stream.mapToInt(i -> i.intValue()).filter(i -> i > 3).sum();
        System.out.println(result);
    }

    @Test
    @DisplayName("test boxed")
    public void test3(){
        int a = 9;

        // requirement: 勾股定理 1..100
        // result int[a,b,c];
        IntStream intStream = IntStream.rangeClosed(1, 100)
                .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0);
//        intStream.forEach(System.out::println);

        // want to return an array, using map? no
        // need to use boxed()
        Stream<int[]> stream1 = intStream.boxed().map(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)});
        stream1.forEach(v-> System.out.println("a="+v[0]+",b="+v[1]+",c="+v[2]));
    }

    @Test
    @DisplayName("test IntStream")
    public void test4(){
        int a = 16;
        IntStream.rangeClosed(1,100).filter(b->Math.sqrt(a*a+b*b)%1==0)
                .boxed()
                .map(b->new int[]{a,b, (int) Math.sqrt(a*a+b*b)})
                .forEach(r->System.out.println("a="+r[0]+",b="+r[1]+",c="+r[2]));
    }

    @Test
    @DisplayName("test mapToObj")
    public void test5(){
        int a = 9;
        IntStream.rangeClosed(1,100).filter(b->Math.sqrt(a*a+b*b)%1==0)
                .mapToObj(b->new int[]{a,b, (int) Math.sqrt(a*a+b*b)})
                .forEach(r->System.out.println("a="+r[0]+",b="+r[1]+",c="+r[2]));
    }

    @Test
    @DisplayName("test mapToObj")
    public void test6() {
        IntStream.range(0,5).mapToObj(AppTest::createThread).forEach(Thread::start);
    }

    private static Thread createThread(final int intName) {
        return new Thread(() -> System.out.println(Thread.currentThread().getName()), "customerThread-" + intName);
    }

}
